package appSocket

import (
	"net"
	"TanguyWeb/main/apphttp"

	"encoding/json"
	"fmt"
	"time"
	"gitee.com/DengAnbang/goutils/loge"
)

func Run(port string) {
	netListen, err := net.Listen("tcp", ":"+port)
	apphttp.CheckErr(err)
	defer netListen.Close()
	loge.W("开始监听链接")
	for {
		conn, err := netListen.Accept()
		if err != nil {
			continue
		}
		loge.E("连接成功请求地址:" + conn.RemoteAddr().String())
		go handleConnection(conn)
	}
}

func handleConnection(conn net.Conn) {
	connUtil := NewConnUtil(conn)
	connUtil.SendMsg(TypeAuth, nil)
	data := make(chan []byte)
	go connUtil.ReadConn(data)
	for {
		select {
		case v, ok := <-data:
			if ok {
				//connUtil.SendMsg(0, "读取到的消息:"+string(v))
				var sm socketMessage
				err := json.Unmarshal(v, &sm)
				if err == nil {
					loge.E("读取到的消息:" + sm.String())
					dispense(&sm, connUtil)
				} else {
					loge.Wf("json解析错误:%s-----err:%s", string(v), err.Error())
				}
			} else {
				loge.E("关闭:" + connUtil.packetID)
				return
			}
		}
	}

}

//分发消息
func dispense(message *socketMessage, packet *packet) {
	//刷新连接的时间
	packet.LastTimeAccessed = time.Now()
	switch message.Type {
	case TypeAuth:
		if s, ok := message.Data.(string); ok {
			pat := socketManage.Get(s)
			if pat != nil {
				pat.SendMsgErr(TypeOtherLogin, "q其他账号登陆")
				socketManage.Close(pat)
			}
			socketManage.Add(s, packet)
			packet.Ping()
		} else {
			packet.SendMsgErr(TypeAuthErr, fmt.Sprintf("认证错误:%s----需要传的type为%s,data为id", string(message.String()), TypeAuth))
		}
	}
}
